package stu.cms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import stu.cms.exection.*;
import stu.cms.pojo.dto.UserDTO;
import stu.cms.pojo.entity.Dept;
import stu.cms.pojo.entity.User;
import stu.cms.mapper.UserMapper;
import stu.cms.result.PageResult;
import stu.cms.service.UserService;
import stu.cms.utils.InfoKit;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    DeptServiceImpl deptService;

    /**
     * 分页查询user列表
     *
     * @param userDTO
     * @return
     */

    public PageResult<User> pageSelect(UserDTO userDTO) {
        Page<User> page = new Page<>(userDTO.getPageNum(), userDTO.getPageSize());

        IPage<User> deptIPage = userMapper.pageWithConditions(page, userDTO);

        Optional.ofNullable(deptIPage).orElseThrow(()->new PageException(OperationConstant.SELECT));
        return new PageResult<>(deptIPage.getRecords(), (int)deptIPage.getTotal());
    }

    /**
     * 增加或者修改用户
     * @param user
     */
    public void saveUser(User user) {
        //所有字段非空验证,并且通过反射赋值
        try {
            boolean flag=InfoKit.isValidAll(user)&&InfoKit.isValidPhone(user.getPhone())
                    &&InfoKit.isValidEmail(user.getEmail());
            if(!flag){
                throw new ValidException("验证不通过");
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new ValidException(e.getMessage());
        }

        List<Dept> list = deptService.list();
        if(list.contains(user.getDept())){
            throw new SaveException("部门不存在");
        }
        //用户名是否重复
        if(this.list().contains(user.getName())){
            throw new SaveException("用户名已存在");
        }

        //添加
        boolean b = this.saveOrUpdate(user);

        if(!b){
            throw new BaseException(OperationConstant.SAVE);
        }
    }

    /**
     * 删除用户
     * @param id
     */
    public void removeUser(Integer id) {
        if(!this.removeById(id))
            throw new BaseException(OperationConstant.DELETE);
    }

}
